package com.androwit.engine.mapping;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.androwit.engine.MappingReader;

public class MappingUtil {

	/**
	 * Reads a one column structure
	 * 
	 * @param idsFile
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static List<Object> readIds(MappingReader reader, File idsFile,
			MappingField key) throws IOException {
		if (!idsFile.canRead()) {
			throw new IllegalStateException(idsFile + " can't be read.");
		}

		FileReader fileReader = null;

		try {
			fileReader = new FileReader(idsFile);
			List<Object> toReturn = new ArrayList<Object>();

			while (reader.readRecord()) {
				toReturn.add(reader.get(key));
			}
			return toReturn;
		} finally {
			if (fileReader != null)
				fileReader.close();
		}

	}

	/**
	 * reads a two columns structure
	 * 
	 * @param fileName
	 * @param keyCol
	 *            key column index
	 * @param valueCol
	 *            value column index
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<Object, Object> readMap(MappingReader reader,
			String fileName, MappingField keyCol, MappingField valueCol)
			throws FileNotFoundException, IOException {
		FileReader fileReader = null;
		try {
			fileReader = new FileReader(fileName);
			Map<Object, Object> toReturn = new HashMap<Object, Object>();
			while (reader.readRecord()) {
				// List<String> line = reader.readLine();
				// toReturn.put(line.get(0), line.get(1));
				toReturn.put(reader.get(keyCol), reader.get(valueCol));
			}
			return toReturn;
		} finally {
			if (fileReader != null)
				fileReader.close();
		}
	}

}
